package com.milloc.db.service.impl;

import com.milloc.db.dto.PageDTO;
import com.milloc.db.dto.PageOutDTO;
import com.milloc.db.entity.DataSourceEntity;
import com.milloc.db.repository.DataSourceEntityRepository;
import com.milloc.db.service.DataSourceService;
import com.milloc.db.service.SQLRunnerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.milloc.db.util.SQLUtils.like;

/**
 * @author gongdeming
 * @create 2019-08-27
 */
@Service
public class DataSourceServiceImpl implements DataSourceService {
    private final DataSourceEntityRepository dataSourceEntityRepository;
    private final SQLRunnerService aSQLRunnerService;

    public DataSourceServiceImpl(DataSourceEntityRepository dataSourceEntityRepository, SQLRunnerService aSQLRunnerService) {
        this.dataSourceEntityRepository = dataSourceEntityRepository;
        this.aSQLRunnerService = aSQLRunnerService;
    }

    @Override
    public DataSourceEntity save(DataSourceEntity dataSourceEntity) {
        if (dataSourceEntity.getId() != null) {
            aSQLRunnerService.reloadDataSource(dataSourceEntity.getId());
        }
        return dataSourceEntityRepository.saveAndFlush(dataSourceEntity);
    }

    @Override
    public void remove(String dataSourceId) {
        aSQLRunnerService.reloadDataSource(dataSourceId);
        dataSourceEntityRepository.deleteById(dataSourceId);
    }

    @Override
    public PageOutDTO<DataSourceEntity> listAll(String dataSourceId, String keyword, PageDTO pageDTO) {
        Page<DataSourceEntity> res = dataSourceEntityRepository.findAll((root, query, builder) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (dataSourceId != null) {
                predicates.add(builder.equal(root.get("id"), dataSourceId));
            }
            if (StringUtils.isNoneBlank(keyword)) {
                String aKeyword = like(keyword);
                Predicate nameLike = builder.like(root.get("name"), aKeyword);
                Predicate descriptionLike = builder.like(root.get("description"), aKeyword);
                predicates.add(builder.and(builder.or(nameLike, descriptionLike)));
            }
            return builder.and(predicates.toArray(new Predicate[]{}));
        }, pageDTO.pageRequest());

        return PageOutDTO.from(res);
    }
}
